#!/usr/bin/env python3
"""
面向 xscreensaver 屏幕保护程序的 MCP Server

提供的 MCP tools 列表：
- xscreensaver_activate: 激活屏幕保护程序，可指定详细模式
- xscreensaver_cycle: 循环切换到下一个屏幕保护程序
- xscreensaver_deactivate: 取消激活屏幕保护程序
- xscreensaver_exit: 退出 xscreensaver 进程
- xscreensaver_lock: 锁定屏幕
- xscreensaver_next: 切换到下一个屏幕保护程序
- xscreensaver_prev: 切换到上一个屏幕保护程序
- xscreensaver_restart: 重启 xscreensaver 守护进程
- xscreensaver_select: 选择指定编号的屏幕保护程序
- xscreensaver_suspend: 暂停屏幕保护程序
- xscreensaver_time: 显示屏幕保护程序的时间信息
- xscreensaver_version: 显示 xscreensaver-command 版本信息
- xscreensaver_watch: 监视屏幕保护程序状态变化
- xscreensaver_demo_help: 显示 xscreensaver-demo 帮助信息
- xscreensaver_demo_version: 显示 xscreensaver-demo 版本信息
- xscreensaver_settings_help: 显示 xscreensaver-settings 帮助信息
- xscreensaver_settings_version: 显示 xscreensaver-settings 版本信息

所有工具返回统一的 JSON 结构：
{
  "success": bool,    # 命令是否成功执行
  "command": str,     # 执行的完整命令
  "exit_code": int,   # 命令退出码
  "stdout": str,      # 标准输出内容
  "stderr": str       # 标准错误内容
}
"""

import subprocess
import shlex
from typing import List, Optional
from mcp.server.fastmcp import FastMCP, Context

mcp = FastMCP("XScreensaver MCP Server")


def run_command(command: List[str]) -> dict:
    """执行命令并返回统一格式的结果"""
    try:
        result = subprocess.run(
            command,
            capture_output=True,
            text=True,
            timeout=30
        )
        return {
            "success": result.returncode == 0,
            "command": " ".join(shlex.quote(arg) for arg in command),
            "exit_code": result.returncode,
            "stdout": result.stdout.strip(),
            "stderr": result.stderr.strip()
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": " ".join(shlex.quote(arg) for arg in command),
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command timed out after 30 seconds"
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(shlex.quote(arg) for arg in command),
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Command execution failed: {str(e)}"
        }


@mcp.tool()
def xscreensaver_activate(verbose: bool = False, quiet: bool = False) -> dict:
    """
    激活屏幕保护程序
    
    参数:
        verbose: 是否启用详细输出模式
        quiet: 是否启用安静模式
    
    返回:
        统一 JSON 结构
    """
    command = ["xscreensaver-command"]
    if quiet:
        command.append("-quiet")
    if verbose:
        command.append("-verbose")
    command.append("-activate")
    
    return run_command(command)


@mcp.tool()
def xscreensaver_cycle() -> dict:
    """
    循环切换到下一个屏幕保护程序
    
    返回:
        统一 JSON 结构
    """
    return run_command(["xscreensaver-command", "-cycle"])


@mcp.tool()
def xscreensaver_deactivate() -> dict:
    """
    取消激活屏幕保护程序
    
    返回:
        统一 JSON 结构
    """
    return run_command(["xscreensaver-command", "-deactivate"])


@mcp.tool()
def xscreensaver_exit() -> dict:
    """
    退出 xscreensaver 进程
    
    返回:
        统一 JSON 结构
    """
    return run_command(["xscreensaver-command", "-exit"])


@mcp.tool()
def xscreensaver_lock() -> dict:
    """
    锁定屏幕
    
    返回:
        统一 JSON 结构
    """
    return run_command(["xscreensaver-command", "-lock"])


@mcp.tool()
def xscreensaver_next(display: Optional[str] = None) -> dict:
    """
    切换到下一个屏幕保护程序
    
    参数:
        display: 指定显示设备（如 :0.0）
    
    返回:
        统一 JSON 结构
    """
    command = ["xscreensaver-command"]
    if display:
        command.extend(["-display", display])
    command.append("-next")
    
    return run_command(command)


@mcp.tool()
def xscreensaver_prev() -> dict:
    """
    切换到上一个屏幕保护程序
    
    返回:
        统一 JSON 结构
    """
    return run_command(["xscreensaver-command", "-prev"])


@mcp.tool()
def xscreensaver_restart() -> dict:
    """
    重启 xscreensaver 守护进程
    
    返回:
        统一 JSON 结构
    """
    return run_command(["xscreensaver-command", "-restart"])


@mcp.tool()
def xscreensaver_select(screen_number: int) -> dict:
    """
    选择指定编号的屏幕保护程序
    
    参数:
        screen_number: 屏幕保护程序编号
    
    返回:
        统一 JSON 结构
    """
    return run_command(["xscreensaver-command", "-select", str(screen_number)])


@mcp.tool()
def xscreensaver_suspend() -> dict:
    """
    暂停屏幕保护程序
    
    返回:
        统一 JSON 结构
    """
    return run_command(["xscreensaver-command", "-suspend"])


@mcp.tool()
def xscreensaver_time() -> dict:
    """
    显示屏幕保护程序的时间信息
    
    返回:
        统一 JSON 结构
    """
    return run_command(["xscreensaver-command", "-time"])


@mcp.tool()
def xscreensaver_version() -> dict:
    """
    显示 xscreensaver-command 版本信息
    
    返回:
        统一 JSON 结构
    """
    return run_command(["xscreensaver-command", "-version"])


@mcp.tool()
def xscreensaver_watch(timeout: int = 10) -> dict:
    """
    监视屏幕保护程序状态变化
    
    参数:
        timeout: 监视超时时间（秒）
    
    返回:
        统一 JSON 结构
    """
    try:
        result = subprocess.run(
            ["xscreensaver-command", "-watch"],
            capture_output=True,
            text=True,
            timeout=timeout
        )
        return {
            "success": True,
            "command": "xscreensaver-command -watch",
            "exit_code": 0,
            "stdout": result.stdout.strip(),
            "stderr": result.stderr.strip()
        }
    except subprocess.TimeoutExpired:
        return {
            "success": True,
            "command": "xscreensaver-command -watch",
            "exit_code": 0,
            "stdout": "Watch command completed (timeout reached)",
            "stderr": ""
        }
    except Exception as e:
        return {
            "success": False,
            "command": "xscreensaver-command -watch",
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Watch command failed: {str(e)}"
        }


@mcp.tool()
def xscreensaver_demo_help(help_type: str = "basic") -> dict:
    """
    显示 xscreensaver-demo 帮助信息
    
    参数:
        help_type: 帮助类型，可选值：basic, all, gapplication, gtk
    
    返回:
        统一 JSON 结构
    """
    if help_type == "all":
        return run_command(["xscreensaver-demo", "--help-all"])
    elif help_type == "gapplication":
        return run_command(["xscreensaver-demo", "--help-gapplication"])
    elif help_type == "gtk":
        return run_command(["xscreensaver-demo", "--help-gtk"])
    else:
        return run_command(["xscreensaver-demo", "--help"])


@mcp.tool()
def xscreensaver_demo_version() -> dict:
    """
    显示 xscreensaver-demo 版本信息
    
    返回:
        统一 JSON 结构
    """
    return run_command(["xscreensaver-demo", "--version"])


@mcp.tool()
def xscreensaver_settings_help(help_type: str = "basic") -> dict:
    """
    显示 xscreensaver-settings 帮助信息
    
    参数:
        help_type: 帮助类型，可选值：basic, all, gapplication, gtk
    
    返回:
        统一 JSON 结构
    """
    if help_type == "all":
        return run_command(["xscreensaver-settings", "--help-all"])
    elif help_type == "gapplication":
        return run_command(["xscreensaver-settings", "--help-gapplication"])
    elif help_type == "gtk":
        return run_command(["xscreensaver-settings", "--help-gtk"])
    else:
        return run_command(["xscreensaver-settings", "--help"])


@mcp.tool()
def xscreensaver_settings_version() -> dict:
    """
    显示 xscreensaver-settings 版本信息
    
    返回:
        统一 JSON 结构
    """
    return run_command(["xscreensaver-settings", "--version"])


if __name__ == "__main__":
    mcp.run()